package com.itheima.reggie.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Dish;
import com.itheima.reggie.domain.DishFlavor;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.DishFlavorMapper;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.Set;

//菜品管理
@Service
@Transactional
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    //分页条件查询

    @Override
    public Page<Dish> findByPage(Integer pageNum, Integer pageSize, String name) {
        //1.构建菜品条件
        LambdaQueryWrapper<Dish> lambdaQueryWrapper1 = new LambdaQueryWrapper<>();
        lambdaQueryWrapper1.like(StrUtil.isNotEmpty(name), Dish::getName, name);
        //2.构建分页
        Page<Dish> page = new Page<>(pageNum, pageSize);
        //3.查询分页
        page = dishMapper.selectPage(page, lambdaQueryWrapper1);

        //4.遍历菜品list集合
        List<Dish> dishList = page.getRecords();
        for (Dish dish : dishList) {
            //4-1查询口味
            //4-1-1构建口味条件
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper2 = new LambdaQueryWrapper<>();
            lambdaQueryWrapper2.eq(DishFlavor::getDishId, dish.getId());
            //4-2-1查询口味列表
            List<DishFlavor> flavorList = dishFlavorMapper.selectList(lambdaQueryWrapper2);
            //4-1-3封装到实体类中
            dish.setFlavors(flavorList);
            //4-2 查询分类
            Category category = categoryMapper.selectById(dish.getCategoryId());
            dish.setCategoryName(category.getName());

        }
        //返回分页对象
        return page;
    }
    //新增菜品


    @Override
    public void save(Dish dish) {

        // 1.直接保存菜品基本信息
        log.info("新增之前id：{}", dish.getId());
        dishMapper.insert(dish);
        log.info("新增之后：{}", dish.getId());//主键返回
        //2.获取并遍历口味
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor dishFlavor : flavorList) {
            // 2-1 关联菜品id
            dishFlavor.setDishId(dish.getId());
            //2-2保存数据库
            dishFlavorMapper.insert(dishFlavor);
        }
        //清理该菜品所属分类的缓存
        String disKey = Constant.DISH + dish.getCategoryId();
        redisTemplate.delete(disKey);




        /*/直接保存菜品基本信息
        log.info("新增之前的id{}", dish.getId());
        dishMapper.insert(dish);
        log.info("新增之后的id{}", dish.getId());//主键返回
        //2.获取并遍历口味
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor flavor : flavorList) {
            //2-1关联菜品id
            flavor.setDishId(dish.getId());
            //2-2保存数据库
            dishFlavorMapper.insert(flavor);
        }*/

    }

    //回显菜品
    @Override
    public Dish findById(Long id) {
        //先查询菜品的基本信息
        Dish dish = dishMapper.selectById(id);
        //2查询口味列表
        //2-1构建条件
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, id);
        //执行2-2执行查询
        List<DishFlavor> flavorList = dishFlavorMapper.selectList(qw);
        //3将口味设置菜品中
        dish.setFlavors(flavorList);
        //4返回菜品
        return dish;
    }

    //菜品修改

    @Override
    public void update(Dish dish) {
        //直接修改菜品基本信息
        dishMapper.updateById(dish);

        //先删除旧口味
        LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
        dqw.eq(DishFlavor::getDishId, dish.getId());
        //根据条件删除
        dishFlavorMapper.delete(dqw);

        //3.遍历新口味
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor dishFlavor : flavorList) {
            // 3-1 关联菜品id
            dishFlavor.setDishId(dish.getId());
            //3-2保存数据库
            dishFlavorMapper.insert(dishFlavor);
        }
        //清理菜品相关的所有缓冲
        //取出所有的key
        Set dishKey = redisTemplate.keys("dish:*");
        //批量删除
        redisTemplate.delete(dishKey);


  /*      //直接修改菜品
        //    信息
        dishMapper.updateById(dish);    //先删除口味
        LambdaQueryWrapper<DishFlavor> qw = new LambdaQueryWrapper<>();
        qw.eq(DishFlavor::getDishId, dish.getId());
        //根据条件删除
        dishFlavorMapper.delete(qw);
        //遍历口味
        List<DishFlavor> flavorList = dish.getFlavors();
        for (DishFlavor dishFlavor : flavorList) {
            //3-1关联菜品id
            dishFlavor.setDishId(dish.getId());
            //3-2保存数据库
            dishFlavorMapper.insert(dishFlavor);

        }*/
    }

    //启停售卖，批量修改 update dish set status =0/1 where in (x,x,x)
    @Override
    public void updateStatus(Integer status, List<Long> ids) {

        //构建条件
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);//where id in（xxx,xxx,xxx)
        //构建修改实体类
        Dish dish = new Dish();
        dish.setStatus(status);
        //执行数据库
        dishMapper.update(dish, qw);


        ///清理该菜品相关的所有缓存
        //  取出所有的key
        Set keys = redisTemplate.keys("dish:*");
        //批量删除
        redisTemplate.delete(keys);


        //构建条件
        /*LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);//where in(x,x,x)
        //构建修改实体类
        Dish dish = new Dish();
        dish.setStatus(status);//set status =0/1
        //执行数据库
        dishMapper.update(dish, qw);*/

    }

    //菜品删除
    @Override
    public void deleteBatchIds(List<Long> ids) {
        //先判断菜品是否是停售状态  select coun（*）  from dish where status=? and id in(x,x,x,)
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);//id in(x,x,x,)
        qw.eq(Dish::getStatus, 1);
        Integer count = dishMapper.selectCount(qw);
        if (count > 0) {
            throw new CustomException("删除的菜品状态必须为已停售");
        }
        //2. 删除菜品  delete from dish where id in (x,x,x)
        dishMapper.deleteBatchIds(ids);

        //删除口味  delete from dish_Flavor where dish_id in (x,x,x)
        LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
        dqw.eq(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(dqw);

        // 清理该菜品相关的所有缓存
        // 1. 取出所有key
        Set keys = redisTemplate.keys("dish:*");
        //批量删除
        redisTemplate.delete(keys);









 /*       //先判断菜品是否是停售状态 select count（*） from dish where status=1 and id in (x,x,x,)
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.in(Dish::getId, ids);//id in (x,x,x)
        qw.eq(Dish::getStatus, 1);//status=1
        Integer count = dishMapper.selectCount(qw);
        if (count > 0) {
            throw new CustomException("删除菜品必需是停售状态");
        }
        //2.删除菜品 delete from dish where id in (x,x,x)
        // LambdaQueryWrapper<Dish> qwe = new LambdaQueryWrapper<>();
        //  qwe.in(Dish::getId, ids);
        // dishMapper.deleteById(qwe);
        dishMapper.deleteBatchIds(ids);
        //3删除口味 delete from dish_flavor where dish_id in (x,x,x)
        LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
        dqw.in(DishFlavor::getDishId, ids);
        dishFlavorMapper.delete(dqw);*/

    }


    @Autowired
    private RedisTemplate redisTemplate;


    //根据分类id+状态查询菜品列表
    @Override
    public List<Dish> findList(Long categoryId, Integer status) {
        //声明返回对象
        List<Dish> dishList = null;
        //1.先查询缓存
        String disKey = Constant.DISH + categoryId;
        dishList  = (List<Dish>) redisTemplate.opsForValue().get(disKey);
        //2。如果有直接返回
        if (dishList != null) {
            log.info("从redis中查询数据");
            return dishList;
        } else {
            //如果没有，查询mysql
            log.info("从mysql中查询数据");
            //1.查询菜品列表
            //. 1-1 构建条件 select * from  dish where category_id =? and status=?
            LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
            qw.eq(Dish::getCategoryId, categoryId);
            qw.eq(Dish::getStatus, status);
            //1-2 mapper查询吗
            dishList = dishMapper.selectList(qw);
            //2.遍历菜品
            for (Dish dish : dishList) {
                //根据菜品的id查询口味
                LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
                dqw.eq(DishFlavor::getDishId, dish.getId());
                List<DishFlavor> flavorList = dishFlavorMapper.selectList(dqw);
                //3. 将口味lieb封装菜品中
                dish.setFlavors(flavorList);
            }
            //将mysql数据，同步到redis中
            redisTemplate.opsForValue().set(disKey, categoryId);
            //fanhuijieg
            return dishList;

        }
        }

        /*1-查询菜品列表
        //1-1构建条件 select * from dish where category_id =? and status =?
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId, categoryId);
        qw.eq(Dish::getStatus, status);
        //1-2 mapper查询
        List<Dish> dishList = dishMapper.selectList(qw);
        //遍历菜品
        for (Dish dish : dishList) {
            //根据菜品的id查询口味
            LambdaQueryWrapper<DishFlavor> dqw = new LambdaQueryWrapper<>();
            dqw.eq(DishFlavor::getDishId, dish.getId());
            List<DishFlavor> flavorList = dishFlavorMapper.selectList(dqw);
            //将口味列表封装到菜品中
            dish.setFlavors(flavorList);

        }
        //返回结果
        return dishList;

    }*/


}